package com.neouton.crm.executiceManager.service.impl;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.entity.ActivitiVO;
import com.neouton.common.util.*;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.IApprovalService;
import com.neouton.crm.dictionary.entity.DictionaryLookupItemVO;
import com.neouton.crm.dictionary.service.IDictionaryService;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.executiceManager.entity.ManagerContractInfoVO;
import com.neouton.crm.executiceManager.mapper.ManagerContractMapper;
import com.neouton.crm.executiceManager.service.IManagerContractService;
import com.neouton.crm.pm.entity.BackMoneyPlanBackEntity;
import com.neouton.crm.pm.entity.BackMoneyPlanVo;
import com.neouton.crm.pm.mapper.ManagerBrAndBmrMapper;
import com.neouton.crm.transpondEmail.service.TranspondEmailService;
import com.neouton.feginClient.FeginService;
import com.neouton.feginClient.WorkFlowFeginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.CompletableFuture;

@Service
public class ManagerContractServiceImpl implements IManagerContractService {

    @Resource
    private ManagerContractMapper managerContractMapper;

    @Resource
    private ManagerBrAndBmrMapper managerBrAndBmrMapper;

    @Resource
    private WorkFlowFeginService workFlowFeginService;

    @Resource
    private IDictionaryService dictionaryService;

    @Resource
    private IApprovalService approvalService;

    @Resource
    private TranspondEmailService transpondEmailService;

    @Resource
    FeginService feginService;

    @Value("${webSit.web}")
    private String webSitUrl;

    @Override
    public PageUtil<ManagerContractInfoVO> queryContractsByPage(IPage page, ManagerContractInfoVO entity, String token) {
        List<SysUserEntity> userList = this.queryUserList(AuthUtils.getUserId(),"managerContractInfo", token);
        IPage<ManagerContractInfoVO> iPage = managerContractMapper.queryContractsByPage(page, entity,userList);
        List<ManagerContractInfoVO> list = iPage.getRecords();
        if(!list.isEmpty()){
            BigDecimal contractAmountPage = new BigDecimal("0");
            for (ManagerContractInfoVO cVo: list) {
                contractAmountPage = contractAmountPage.add(new BigDecimal(cVo.getContractAmount()));
            }
            list.get(0).setContractAmountPage(String.valueOf(contractAmountPage));
            iPage.setRecords(list);
        }
        return new PageUtil(iPage);
    }

    @Override
    public Integer saveOrUpdateContractInfo(ManagerContractInfoVO contractInfo, String token) {
        //1.发起工作流
        //1）获取下一审批人，暂定总经理
        //获取审批人
        SysUserEntity user = dictionaryService.queryMenuUserIdsByCode("administrativeSpecialist").get(0);
        //获取人员信息
        Integer businessId = this.startContractApproval();
        //2.记录本地审批数据
        //生成审批主表信息，日志信息
        ApprovalVO approval = approvalService.initApprovalAndLog(businessId, 47, contractInfo.getAskReason(),
                "", -1,"");
        //之后更新/保存
        contractInfo.setApprovalId(approval.getApprovalId());

        //保存，更新综管合同信息
        if( null == contractInfo.getContractId() ){
            contractInfo.setContractNo(contractInfo.getContractNo().replace("...",this.getContractMaxNumByDate()));
            managerContractMapper.saveContractInfo(contractInfo);
            //保存回款计划
            saveBackMoneyPlan(contractInfo);
        }else {
            managerContractMapper.backUpContractInfo(contractInfo.getContractId(), AuthUtils.getUserId());
            managerContractMapper.updateContractInfo(contractInfo);
            //修改回款计划
            updateBackMoneyPlan(contractInfo);
        }
        //保存转发人
        transpondEmailService.insertTranspondEmailInfoByUser(contractInfo.getApprovalId(),contractInfo.getForwardUsers());
        if(AuthUtils.getUserAccount().equals(user.getAccount())){
            //跳过第一步审批
            this.approveContractInfo(contractInfo,token,true);
        }else {
            //发送审批邮件
            //发送邮件
//            String titel = "【系统通知】综管合同信息 - 流程单审批通知";
//            String msg =  "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                    "<div><p style='text-indent: 2em'>您好，您有一张新的综管合同信息需要处理：</p></div>"+
//                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请人："+ AuthUtils.getUserName() + " / " + AuthUtils.getUserAccount() + "</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请原因："+(StringUtils.isEmpty(contractInfo.getAskReason()) ? "无":contractInfo.getAskReason()) + "</p></div>"+
//                    "<div><p style='text-indent: 2em'>申请时间："+ DateUtils.getCurrentTime()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>合同名称："+contractInfo.getContractTopic()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>合同编号："+contractInfo.getContractNo()+"</p></div>"+
//                    "<div><p style='text-indent: 2em'>合同金额："+contractInfo.getContractAmount()+"元</p></div>"+
//                    "<div><p style='text-indent: 2em'>回款期次：共"+contractInfo.getBmpPeriod()+"期</p></div>"+
//                    "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                    "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
//                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
//                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),null,titel,msg,token));
            //调用通知接口生成待办通知
            Integer userId = AuthUtils.getUserId();
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(approval.getApprovalId(), new Timestamp(System.currentTimeMillis()),
                    userId,0,47,user.getUserId(),token));
            approvalService.updateNextApproverByApprovalId(user.getUserId(),contractInfo.getApprovalId());
        }
        return contractInfo.getContractId();
    }

    //保存回款计划
    private void saveBackMoneyPlan(ManagerContractInfoVO contractInfo) {
        List<BackMoneyPlanVo> backMoneyPlanList = contractInfo.getBackMoneyPlanList();
        for (BackMoneyPlanVo backMoneyPlanVo : backMoneyPlanList) {
            backMoneyPlanVo.setContractId(contractInfo.getContractId());
            backMoneyPlanVo.setIsBm(0);
        }
        managerContractMapper.saveBackMoneyPlan(backMoneyPlanList);
    }
    //修改回款计划
    private void updateBackMoneyPlan(ManagerContractInfoVO contractInfo) {
        //在回款计划备份表中 --保存回款计划
        //根据合同id 查询得到回款计划，将结果写入回款计划备份表中
        List<BackMoneyPlanVo> backMoneyPlanByContractId = managerBrAndBmrMapper.getBackMoneyPlanByContractId(contractInfo.getContractId());
        ArrayList<BackMoneyPlanBackEntity> backMoneyPlanBackEntities = new ArrayList<>();
        for (BackMoneyPlanVo backMoneyPlanVo : backMoneyPlanByContractId) {
            BackMoneyPlanBackEntity backMoneyPlanBackEntity = new BackMoneyPlanBackEntity();
            BeanUtils.copyProperties(backMoneyPlanVo,backMoneyPlanBackEntity);
            backMoneyPlanBackEntity.setApprovalId(contractInfo.getApproval().getApprovalId());
            backMoneyPlanBackEntities.add(backMoneyPlanBackEntity);
        }
        //写入回款计划备份表
        managerBrAndBmrMapper.saveBackMoneyPlanBack(backMoneyPlanBackEntities);

        List<BackMoneyPlanVo> backMoneyPlanList = contractInfo.getBackMoneyPlanList();
        for (BackMoneyPlanVo backMoneyPlanVo : backMoneyPlanList) {
            managerBrAndBmrMapper.deleteBackMoneyPlan(backMoneyPlanVo);
            if(backMoneyPlanVo.getBmpId() != null){
                backMoneyPlanVo.setBmpId(null);
            }else{
                backMoneyPlanVo.setContractId(contractInfo.getContractId());
                backMoneyPlanVo.setIsBm(0);
            }
        }
        managerContractMapper.saveBackMoneyPlan(backMoneyPlanList);
    }


    @Override
    public ManagerContractInfoVO queryContractInfoByapprovalId(Integer approvalId) {
        ManagerContractInfoVO contractInfo = managerContractMapper.queryContractInfoByapprovalId(approvalId);
        contractInfo.setForwardUsers(transpondEmailService.queryTranspondByApprovalId(approvalId));
        return contractInfo;
    }

    @Override
    public ManagerContractInfoVO getContractInfoHistoryByApprovalId(Integer approvalId) {
        ManagerContractInfoVO contractInfo = managerContractMapper.queryContractInfoHistoryByApprovalId(approvalId);
        if(contractInfo == null){
            contractInfo = managerContractMapper.queryContractInfoByapprovalId(approvalId);
        }
        contractInfo.setForwardUsers(transpondEmailService.queryTranspondByApprovalId(approvalId));
        return contractInfo;
    }

    @Override
    public ManagerContractInfoVO queryContractInfoById(Integer contractId) {
        ManagerContractInfoVO contractInfo = managerContractMapper.queryContractInfoById(contractId);
        contractInfo.setForwardUsers(transpondEmailService.queryTranspondByApprovalId(contractInfo.getApproval().getApprovalId()));
        return contractInfo;
    }

    @Override
    public Boolean rejectionContractInfo(ManagerContractInfoVO contractInfo, String token) {
        //获取工作流ID
        ApprovalVO approval = approvalService.queryApprovalByAppID(contractInfo.getApprovalId());

        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
//        //获取当前所处节点
//        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
        //删除流程实例
        workFlowFeginService.deleteInstance(activitiVO);
        //驳回至上一节点
//        workFlowFeginService.rejectedByBusinessId(activitiVO);
        SysUserEntity user = null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(), token).getResult();
//        if( "商务审批".equals(processNodeNameAndCode.getResult().getName()) ){
        user = askUser;
        //驳回至起点
        workState = 1;
        titel= "【系统通知】综管合同信息 - 流程单审批驳回通知";
        msg =  "<div><p >" + "尊敬的" + askUser.getLoginName() + "：</p></div>" +
                "<div><p style='text-indent: 2em'>您好，您申请的综管合同信息已被驳回：</p></div>"+
                "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                "<div><p style='text-indent: 2em'>审批人："+AuthUtils.getUserName() + " / " + AuthUtils.getUserAccount() +"</p></div>"+
                "<div><p style='text-indent: 2em'>审批意见："+(StringUtils.isEmpty(contractInfo.getAppReason()) ? "无":contractInfo.getAppReason()) +"</p></div>"+
                "<div><p style='text-indent: 2em'>审批时间："+DateUtils.getCurrentTime()+"</p></div>"+
                "<div><p style='text-indent: 2em'>合同名称："+contractInfo.getContractTopic()+"</p></div>"+
                "<div><p style='text-indent: 2em'>合同编号："+contractInfo.getContractNo()+"</p></div>"+
                "<div><p style='text-indent: 2em'>合同金额："+contractInfo.getContractAmount()+"元</p></div>"+
                "<div><p style='text-indent: 2em'>回款期次：共"+contractInfo.getBmpPeriod()+"期</p></div>"+
                "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 项目信息管理 - 项目信息 " +
                "<a href='"+webSitUrl+"/?m=crm&p=projectmanage&me=projectmanageInfo'>进入</a></p></div>"+
                "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
        approvalService.approvalRejection(null,contractInfo.getApprovalId());
        todoUser = 0;
//        }else {
//            if("财务审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("administrativeSpecialist").get(0);
//            }else if("售后审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
//            }else if("总经理审批".equals(processNodeNameAndCode.getResult().getName())){
//                user = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
//            }
//            workState = 0;
//            titel = "【系统通知】综管合同信息审批待处理通知";
//            msg =  initContractEmailData(user.getLoginName(),"您有一张新的综管合同信息已被上级驳回，需要处理"
//                    ,approval.getApprovalCode(), askUser.getLoginName(),contractInfo.getContractTopic(),contractInfo.getContractNo(),contractInfo.getContractAmount(),
//                    contractInfo.getBmpPeriod());
//            todoUser = user.getUserId();
//            approvalService.updateNextApproverByApprovalId(user.getUserId(),contractInfo.getApprovalId());
//        }
        //记录日志
        approvalService.insertApprovalLog(approval.getApprovalId(),"驳回",
                "",contractInfo.getAppReason());
        SysUserEntity finalUser = user;
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(),null,titel,msg,token));
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(contractInfo.getApprovalId(),  approval.getCreateDataTime(),
                approval.getCreator(),workState,47,todoUser,token));
        return true;
    }

    @Override
    public Boolean approveContractInfo(ManagerContractInfoVO contractInfo, String token, Boolean auto) {
        //获取工作流ID
        ApprovalVO approval = approvalService.queryApprovalByAppID(contractInfo.getApprovalId());
        ActivitiVO activitiVO = new ActivitiVO();//最终审批人
        activitiVO.setBusinessId(approval.getBusinessId());
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        //获取当前所处节点
        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
        SysUserEntity user = null;
        Integer workState;
        String titel;
        String msg;
        Integer todoUser;
        String ccUser = null;
        SysUserEntity askUser = feginService.searchUserInfoById(approval.getCreator(), token).getResult();
        //记录审批日志
        if(auto){
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "系统判定跳过",contractInfo.getAppReason());
        }else {
            //记录日志
            approvalService.insertApprovalLog(approval.getApprovalId(),"通过",
                    "",contractInfo.getAppReason());
        }
        if( "董事长审批".equals(processNodeNameAndCode.getResult().getName()) ){
            //审批通过
            workFlowFeginService.approvalProcessByBusinessId(activitiVO);
            user=askUser;
            workState = 1;
            todoUser = 0;
            titel = "【系统通知】综管合同信息 - 流程单审批通过通知";
            msg =  "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
                    "<div><p style='text-indent: 2em'>您好，您申请的综管合同审批已通过：</p></div>"+
                    "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>合同名称："+contractInfo.getContractTopic()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>合同编号："+contractInfo.getContractNo()+"</p></div>"+
                    "<div><p style='text-indent: 2em'>合同金额："+contractInfo.getContractAmount()+"元</p></div>"+
                    "<div><p style='text-indent: 2em'>回款期次：共"+contractInfo.getBmpPeriod()+"期</p></div>"+
                    "<div><p style='text-indent: 2em'>系统查看路径：客户关系管理系统 - 项目信息管理 - 项目信息 " +
                    "<a href='"+webSitUrl+"/?m=crm&p=projectmanage&me=projectmanageInfo'>进入</a></p></div>"+
                    "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
                    "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
            ccUser = this.queryManagerContractCC();
            approvalService.approved(null,contractInfo.getApprovalId());
            String transpondEmails = transpondEmailService.selectTranspondEmailStr(contractInfo.getApprovalId());
            if(!transpondEmails.isEmpty()){
                ccUser = ccUser + "," + transpondEmails;
            }
            String finalCcUser = ccUser;
            SysUserEntity finalUser = user;
            CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(), finalCcUser,titel,msg,token));
            CompletableFuture.runAsync(() -> NoticUtils.pushNotic(contractInfo.getApprovalId(),  approval.getCreateDataTime(),
                    approval.getCreator(),workState,47,todoUser,token));
        }else {
            //动态获取下一步审批人员以及流程，设置参数
            if("行政专员审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("personnelManager").get(0);
                activitiVO.getCustomParams().put("personnelManager",user.getAccount());
            }else if("人事经理审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
                activitiVO.getCustomParams().put("finance",user.getAccount());
            }else if("财务审批".equals(processNodeNameAndCode.getResult().getName())){
                user = dictionaryService.queryMenuUserIdsByCode("chairman").get(0);
                activitiVO.getCustomParams().put("chairman",user.getAccount());
            }
            //审批通过（使用动态入参传入下一审批人）
            workFlowFeginService.approvalProcessCustomUserByBusinessId(activitiVO);
            //获取下一节点
            ResponseAPI<ActivitiVO> nextProcessNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
            if(nextProcessNodeNameAndCode.getResult().getAssignee().equals(processNodeNameAndCode.getResult().getAssignee())){ //记录日志
                this.approveContractInfo(contractInfo,token,true);
            }else {
                workState = 0;
                todoUser = user.getUserId();
                //交由下一审批人处理
//                titel = "【系统通知】综管合同信息 - 流程单审批通知";
//                msg =   "<div><p >" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                        "<div><p style='text-indent: 2em'>您好，您有一张新的综管合同信息需要处理：</p></div>"+
//                        "<div><p style='text-indent: 2em'>事项编号："+approval.getApprovalCode()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>申请人："+ AuthUtils.getUserName() + " / " + AuthUtils.getUserAccount() + "</p></div>"+
//                        "<div><p style='text-indent: 2em'>申请原因："+(StringUtils.isEmpty(contractInfo.getAskReason()) ? "无":contractInfo.getAskReason())+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>申请时间："+DateUtils.getCurrentTime()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>合同名称："+contractInfo.getContractTopic()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>合同编号："+contractInfo.getContractNo()+"</p></div>"+
//                        "<div><p style='text-indent: 2em'>合同金额："+contractInfo.getContractAmount()+"元</p></div>"+
//                        "<div><p style='text-indent: 2em'>回款期次：共"+contractInfo.getBmpPeriod()+"期</p></div>" +
//                        "<div><p style='text-indent: 2em'>系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                        "<a href='"+webSitUrl+"/?m=crm&p=crmtodoItems&me=todoApprovalPath'>进入</a></p></div>"+
//                        "<div><p style='text-indent: 2em'>谢谢！</p></div>"+
//                        "<div><p style='text-indent: 2em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
//                String finalCcUser = ccUser;
//                SysUserEntity finalUser = user;
//                CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(finalUser.getEmail(), finalCcUser,titel,msg,token));
                approvalService.updateNextApproverByApprovalId(user.getUserId(),contractInfo.getApprovalId());
                CompletableFuture.runAsync(() -> NoticUtils.pushNotic(contractInfo.getApprovalId(),  approval.getCreateDataTime(),
                        approval.getCreator(),workState,47,todoUser,token));
            }
        }
        return true;
    }

    @Override
    public void exportContractInfo(HttpServletResponse response, ManagerContractInfoVO entit, String token) throws Exception {
        List<SysUserEntity> userList = this.queryUserList(AuthUtils.getUserId(),"managerContractInfo", token);
        List<ManagerContractInfoVO> contractInfos = managerContractMapper.queryAllContractInfos(entit,userList);
        List<String> codes = new ArrayList<>();
        codes.add("paymentPeriod");
        Map<String, List<DictionaryLookupItemVO>> stringListMap = dictionaryService.queryDictionaryLookupInfo(null, codes);
        for (int i = 0; i < contractInfos.size(); i++) {
            ManagerContractInfoVO contractInfo = contractInfos.get(i);
            contractInfo.setContractId(i+1);
            //付款期次
            for(DictionaryLookupItemVO dictionaryLookupItemVO : stringListMap.get("paymentPeriod") ){
                if(dictionaryLookupItemVO.getItemCode().equals(contractInfo.getBmpPeriod()+"")){
                    contractInfo.setBmpPeriodStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }

            if(0 == contractInfo.getApproval().getApprovalStatus()){
                contractInfo.setApprovalStr("审批中");
            }else if(1 == contractInfo.getApproval().getApprovalStatus()){
                contractInfo.setApprovalStr("已通过");
            }else if(2 == contractInfo.getApproval().getApprovalStatus()){
                contractInfo.setApprovalStr("已驳回");
            }else if(3 == contractInfo.getApproval().getApprovalStatus()){
                contractInfo.setApprovalStr("已撤回");
            }else if(5 == contractInfo.getApproval().getApprovalStatus()){
                contractInfo.setApprovalStr("撤回中");
            }
            contractInfo.setContractSigningDateStr(String.format("%tY-%<tm-%<td",contractInfo.getContractSigningDate()));
        }

        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String contractTemplatePath = String.valueOf(properties.get("report.managerContractTemplate"));

        //依据根目录获取模板位置
        TemplateExportParams params = new TemplateExportParams(contractTemplatePath);
        Map<String, Object> map = new HashMap<>();
        map.put("contractInfos",contractInfos);
        ReportUtils.exportExcel(params,map,"综管合同列表",response);
    }


    /**
     * 删除综管合同
     * @param contractId
     * @return
     */
    public Boolean deleteContractInfoById(Integer contractId){
        return managerContractMapper.deleteContractInfoById(contractId);
    }

    private List<SysUserEntity> queryUserList(Integer userId,String authCode, String token) {
        List<SysUserEntity> userList = new ArrayList<>();
        List<SysUserEntity> authUserIList = dictionaryService.queryAuthUserIdsByCode(authCode);
        boolean result = false;
        for (SysUserEntity user:authUserIList) {
            if (Objects.equals(user.getUserId(), userId)) {
                result = true;
            }
        }
        if (result) {
            userList = feginService.getUserIgnoreFlag(token).getResult();
        } else {
            SysUserEntity user = feginService.searchUserInfoByIds(userId,token).getResult();
            if (user.getIsLeader() == 1) {
                userList = feginService.recursiveQueryAllUserByLeaderId(userId, token).getResult();
            }
            userList.add(user);
        }
        return userList;
    }

    /**
     * 开启审批流程
     * @return
     */
    private Integer startContractApproval(){
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setProcessName("综管合同审批");
        activitiVO.setProcessCode("manager_contract_approval");
//        activitiVO.setVersion("1");
        activitiVO.setNextNodeParams("administrativeSpecialist");
//        HashMap<String,Object> customParams = new HashMap<>();
        //商务负责人
        SysUserEntity business = dictionaryService.queryMenuUserIdsByCode("administrativeSpecialist").get(0);
        activitiVO.setNextNodeAssignee(business.getAccount());

//        customParams.put("administrativeSpecialist",business.getAccount());
//        //财务负责人
//        SysUserEntity finance = dictionaryService.queryMenuUserIdsByCode("finance").get(0);
//        customParams.put("finance",finance.getAccount());
//        //售后负责人
//        SysUserEntity afterSales = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
//        customParams.put("afterSales",afterSales.getAccount());
//        //总经理
//        SysUserEntity president = dictionaryService.queryMenuUserIdsByCode("president").get(0);
//        customParams.put("president",president.getAccount());
//        activitiVO.setCustomParams(customParams);
        ResponseAPI<ActivitiVO> responseAPI = workFlowFeginService.startMaxVersionProcessByDesignCodeCustomParams(activitiVO);
        return responseAPI.getResult().getBusinessId();
    }

    /**
     * 获取当日最大合同单号
     * @return
     */
    private String getContractMaxNumByDate(){
        Integer num = managerContractMapper.getContractMaxNumByDate();
        if(num<10)
            return "0"+num;
        else
            return num.toString();
    }

    /**
     * 获取合同抄送人
     * @return
     */
    private String queryManagerContractCC(){
        //获取抄送人
        List<SysUserEntity> userIds = dictionaryService.queryCcUserIdsByCode("contractCC");
        StringBuilder emailList = new StringBuilder();
        for (int i = 0; i < userIds.size(); i++) {
            if (userIds.size()-1 == i){
                emailList.append(userIds.get(i).getEmail());
            }else {
                emailList.append(userIds.get(i).getEmail());
                emailList.append(",");
            }
        }
        return emailList.toString();
    }

    /**
     * 分页查询待办信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<ManagerContractInfoVO> queryApprovalContractByPage(IPage page, ManagerContractInfoVO entity){
        //获取工作流待办
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<List<ActivitiVO>> workFlowVoResponseAPI = workFlowFeginService.getTasksByAuthorization(activitiVO);
        List<ActivitiVO> activitiVOS = workFlowVoResponseAPI.getResult();
        if( activitiVOS == null || activitiVOS.size() == 0 ){
            return new PageUtil(new PageDTO());
        }else{
            return new   PageUtil( managerContractMapper.queryApprovalContractByPage(page, entity,activitiVOS));
        }
    }

    /**
     * 分页查询已办信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<ManagerContractInfoVO> queryApprovalContractDoneByPage(IPage page, ManagerContractInfoVO entity){
        IPage<ManagerContractInfoVO> iPage = managerContractMapper.queryApprovalContractDoneByPage(page, entity);
        return new PageUtil(iPage);
    }


    /**
     * 分页查询申请记录信息
     *
     * @param page
     * @param entity
     * @return
     */
    public PageUtil<ManagerContractInfoVO> queryApprovalContractRecordByPage(IPage page, ManagerContractInfoVO entity,String token){
        List<SysUserEntity> userList = this.queryUserList(AuthUtils.getUserId(),"approvalRecord", token);
        IPage<ManagerContractInfoVO> iPage = managerContractMapper.queryApprovalContractRecordByPage(page, entity,userList);
        return new PageUtil(iPage);
    }
}
